/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package multiface.promonet.servlet.section;

import java.io.IOException;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import multiface.promonet.jpa.Utente;
import multiface.promonet.jpa.util.PersistenceManager;
import multiface.promonet.servlet.section.action.ActionFile;
import multiface.web.util.Define;

/**
 *
 * @author diego
 */
public class Account {

    /**
     * Dispatcher per gestire le action della sezione Account
     *
     * @param request
     * @param response
     * @throws IOException
     */
    public static void dispatcher(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String action = request.getParameter("action");
        if (action.equalsIgnoreCase("mod_login")) {
            Account.modLogin(request, response);
        }
        if (action.equalsIgnoreCase("set_cover_photo")) {
            Account.setCoverPhoto(request, response);
        }
        if (action.equalsIgnoreCase("del_photo")) {
            Account.delPhoto(request, response);
        }
    }

    public static void modLogin(HttpServletRequest request, HttpServletResponse response) {
        HttpSession s = request.getSession();
        if (s.getAttribute(Define.USER_SESSION) != null) {

            Utente u_session = (Utente) s.getAttribute(Define.USER_SESSION);

            EntityManagerFactory emf = PersistenceManager.getInstance().getEntityManagerFactory();
            EntityManager em = emf.createEntityManager();

            Utente u = em.find(Utente.class, u_session.getIdutente());

            u.setNome(request.getParameter("name"));
            u.setCognome(request.getParameter("surname"));
            u.setEmail(request.getParameter("email"));
            u.setPassword(request.getParameter("password"));

            em.getTransaction().begin();
            em.persist(u);
            em.getTransaction().commit();

            em.close();
        }
    }

    public static void setCoverPhoto(HttpServletRequest request, HttpServletResponse response) {
        ActionFile.setCoverFile(request, response);
    }

    public static void delPhoto(HttpServletRequest request, HttpServletResponse response) {
        ActionFile.delFile(request, response);
    }
}
